package com.mission.shaco.warehouse

import android.os.Bundle

import android.content.Context
import android.content.Intent
import android.support.constraint.ConstraintLayout
import android.text.TextUtils
import android.widget.TextView
import android.view.ViewGroup
import android.view.LayoutInflater
import android.view.View
import android.widget.AdapterView
import android.widget.BaseAdapter
import com.androidquery.AQuery
import com.androidquery.callback.AjaxCallback
import com.androidquery.callback.AjaxStatus
import com.mission.shaco.warehouse.models.ClientConfig
import com.mission.shaco.warehouse.models.ClientConfig.getStockStatusColor
import com.mission.shaco.warehouse.models.ClientConfig.getStockStatusLabel
import kotlinx.android.synthetic.main.activity_stock_change_by_stock.*
import org.json.JSONArray
import org.json.JSONObject


class StockChangeByStockActivity : ScannerActivity(),   AdapterView.OnItemClickListener {
    override fun onItemClick(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
        when(parent?.id){
            list_stock_item.id -> {
                var vh = view?.tag as ViewHolder
                var intent: Intent = Intent(this, StockChangeActivity::class.java)
                intent.putExtra("webitemid",vh.webitemid.getText())
                selectViewHolder = vh
                this.startActivityForResult(intent,1)
            }
        }
    }

    private var selectViewHolder:ViewHolder? = null



    private var data: JSONArray = JSONArray()

    var searchThread: Runnable = Runnable {
        try {
            val aq: AQuery = AQuery(this)
            val params = HashMap<String, Any>()

            var map = JSONObject()
            map.put("opeater",getOpreateName())
            map.put("stock", txtStockSearch.getText())
            params.put("datas", map)
            var jsonStr = map.toString()

            aq.ajax(ClientConfig.getHostUrl(ClientConfig.JOSN_GET_STOCK_INFO),params, String::class.java,  object : AjaxCallback<String>() {

                override fun callback(url: String, result: String, status: AjaxStatus) {
                    if(status.code == 200){
                        var response: JSONObject = JSONObject(result)
                        if(response.getInt("status") == 1) {
                            data = response.getJSONArray("products")
                            var length = data.length()
                            txtResultTotal.setText(length.toString())
                            getAdapter().reload()
                        }else{
                            noticeMessage("未找到产品")
                        }
                    }else{
                        noticeMessage("网络出问题")
                    }
                }
            })

        } catch (e: InterruptedException) {
            e.printStackTrace()
        }
    }

    fun getAdapter() : MyAdapter {
        return list_stock_item.adapter as MyAdapter
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_stock_change_by_stock)

        val adapter = MyAdapter(this)
        list_stock_item.setAdapter(adapter)
        list_stock_item.setOnItemClickListener (this)
        btnFinish.setOnClickListener(this)
        btnSearch.setOnClickListener(this)
    }

    override fun onClick(v: View?) {
        when(v?.id){
            btnSearch.id-> reload()
            btnFinish.id->{ finish()}
        }
    }

    fun reload(){
        var t = Thread(searchThread)
        t.start()
    }

    override fun afterScanReceive() {
        if(!TextUtils.isEmpty(code)){
            txtStockSearch.setText(code)
            successNotice()
            reload()
            code = ""
        }
    }

    /**
     *  配货匹配成功提示
     */
    fun successNotice(){
        player.start()
        vibrator.vibrate(800)
    }

    /**
     *  配货匹配失败提示
     */
    fun failedNotice(){
        vibrator.vibrate(300)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        reload()
    }

    //ViewHolder静态类
    internal class ViewHolder(row:View?) {
        var name: TextView
        var status: TextView
        var stock: TextView
        var webitemid: TextView
        var layout: ConstraintLayout

        init {
            this.name = row?.findViewById ( R.id.txtProductName ) as TextView
            this.status = row?.findViewById ( R.id.txtProductStatus ) as TextView
            this.stock = row?.findViewById ( R.id.txtProductStock ) as TextView
            this.webitemid = row?.findViewById ( R.id.txtProductSKU ) as TextView
            this.layout = row?.findViewById(R.id.layoutStockItem) as ConstraintLayout
        }
    }

    inner class MyAdapter (context: Context) : BaseAdapter() {
        private var mInflater: LayoutInflater? = null

        init {
            this.mInflater = LayoutInflater.from(context)
        }

        override fun getCount(): Int {
            return data!!.length()
        }

        fun reload(){
            notifyDataSetChanged()
        }

        override fun getItem(position: Int): Any {
            return data!!.get(position)
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
            var view = convertView
            var vh: ViewHolder? = null

            if (convertView == null) {
                view = this.mInflater!!.inflate(R.layout.list_stock_change_row, parent, false)
                vh = ViewHolder(view)
                view.tag = vh

            } else {
                view = convertView
                vh = view.tag as ViewHolder
            }

            var item = this.getItem(position) as JSONObject


            vh.name.text = item.getString("znName")
            vh.status.text = getStockStatusLabel(item.getString("Stockstate"))
            vh.stock.text = item.getString("position")
            vh.webitemid.text = item.getString("webitemid")

            var color = getStockStatusColor(item.getString("Stockstate"))
            vh.layout.setBackgroundColor(getResources().getColor(color))

            return view
        }

    }

}

